<?php
declare (strict_types = 1);

namespace app\admin\controller;
use app\admin\validate\AdminValidate;
use app\admin\validate\AdminValidate2;
use app\admin\validate\AdminValidate3;
use think\facade\Db;
use think\Validate;
use app\middleware\Auth;
class Index
{
    /**

    --
    -- 表的结构 `admin`
    --

    CREATE TABLE `admin` (
    `admin_id` int NOT NULL COMMENT 'id',
    `admin_name` varchar(15) DEFAULT NULL COMMENT '账户',
    `admin_head` varchar(255) DEFAULT NULL COMMENT '头像',
    `admin_password` varchar(255) DEFAULT NULL COMMENT '密码',
    `admin_status` mediumint DEFAULT '0' COMMENT '状态0:正常，1封禁',
    `error_num` int NOT NULL DEFAULT '0' COMMENT '登录错误次数',
    `error_time` date NOT NULL DEFAULT '1970-01-01' COMMENT '错误日期',
    `admin_create_time` datetime DEFAULT NULL COMMENT '创建时间'
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

    --
    -- 转存表中的数据 `admin`
    --

    INSERT INTO `admin` (`admin_id`, `admin_name`, `admin_head`, `admin_password`, `admin_status`, `error_num`, `error_time`, `admin_create_time`) VALUES
    (1, 'admin', 'https://blqcs.yyuebd.com/storage/uploads/20221124/c2eb2ccfe9aeee92d0a1ee0127d2f1d1.jpg', '$2y$10$4riNK0pzHLM9jBLPuuMjP.8GpCI4HtsHQaYiyTcRIs/dTYyBjsm.m', 0, 0, '2022-12-28', '2022-08-24 18:13:40');

    --
    -- 转储表的索引
    --

    --
    -- 表的索引 `admin`
    --
    ALTER TABLE `admin`
    ADD PRIMARY KEY (`admin_id`),
    ADD UNIQUE KEY `admin_name` (`admin_name`);

    --
    -- 在导出的表使用AUTO_INCREMENT
    --

    --
    -- 使用表AUTO_INCREMENT `admin`
    --
    ALTER TABLE `admin`
    MODIFY `admin_id` int NOT NULL AUTO_INCREMENT COMMENT 'id', AUTO_INCREMENT=2;
    COMMIT;

     */
    protected $middleware = [
        Auth::class =>[ 'except'=>['login','getUser'] ],//except：除了之外
    ];
    protected function getUser($username){
        return  Db::table("admin")->where(['admin_name'=>trim($username)])->find();
    }
    public function login()
    {
        $max_error_num = 5;
        $data = request()->param();
        //$data = ['username'=>'admin','password'=>'123456789'];
        $AdminValidate =  new AdminValidate();
        if($AdminValidate->scene('admin_login')->check($data)){
            $user = $this->getUser($data['username']);
            if(empty($user)){//不存在该用户
                return json(['status'=>500,'msg'=>'当前用户不存在！']);
            }else if($user['admin_status']){//当前用户被封禁
                return json(['status'=>500,'msg'=>'当前用户被封禁！']);
            }else if($user['error_num']>=$max_error_num&&$user['error_time']==date("Y-m-d")){//连续输错密码次数过多
                return json(['status'=>500,'msg'=>'连续输错密码'.$max_error_num.'次密码,明日再试！']);
            }else{
                $check = checkPassword($data['password'],$user['admin_password']);
                if($check['status']==200){//验证通过

                    if(time()>strtotime($user['end_time'])){
                        return json([
                            'status'=>500,
                            'msg'=>'抱歉当前账户已过期！无法登录!'
                        ]);
                    }
                    $status = 200;
                    $msg = "登录成功！";
                    $username = $data['username'];
                    $token = signToken($user['admin_id']);
                    Db::table("admin")->where(['admin_name'=>trim($data['username']),'admin_status'=>0])->update([
                        'error_time'=>date('Y-m-d'),
                        'error_num'=>0
                    ]);
                }else{
                    if($user['error_time']!=date("Y-m-d")){
                        Db::table("admin")->where(['admin_name'=>trim($data['username']),'admin_status'=>0])->update([
                            'error_num'		=>	1,
                            'error_time'	=>	date('Y-m-d')
                        ]);
                    }else{
                        Db::table("admin")->where(['admin_name'=>trim($data['username']),'admin_status'=>0])->update([
                            'error_num'		=>	Db::raw('error_num+1'),
                            'error_time'	=>	date('Y-m-d')
                        ]);
                    }
                    $user2 = $this->getUser($data['username']);
                    $status = 500;
                    $msg = $user2['error_num']<$max_error_num?"密码错误！您还可以输入" . ($max_error_num - $user2['error_num']) .'次。':'连续输错密码'.$max_error_num.'次密码,明日再试！';
                    $username = '';
                    $token ='';
                }
                return json(['status'=>$status,'msg'=>$msg,'user'=>$username,'token'=>$token]);
            }
        }else{
            return json(['status'=>500,'msg'=>$AdminValidate->getError()]);
        }
    }
    public function getInfo(){
        $token = request()->header('token');
        $checkToken = checkToken($token);
        $user = Db::table("admin")->where(['admin_id'=>$checkToken['data']->uid])
            ->filter(function ($user){
                $auth_group = Db::table('think_auth_group')->where('id',$user['admin_roles'])->find();
                $user['roles'] = $auth_group['roles'];
                $user['admin_title'] = $auth_group['title'];
                return $user;
            })
            ->field('admin_roles,admin_name,admin_head,end_num,end_time')
            ->find();
        return json(['status'=>200,'msg'=>'ok','data'=>$user]);
    }
    public function headUpload(){
        $size = 2097152;//2M
        $fileType = "jpg,jpeg,png,gif,bmp";
        $headFile = fileUpload($size,$fileType);
        return json($headFile);
    }
    public function Upload2(){
        $index = request()->param('index');
        $size = 2097152;//2M
        $fileType = "jpg,jpeg,png,gif,bmp";
        $headFile = fileUpload($size,$fileType);
        $headFile['index'] = (int)$index;
        return json($headFile);
    }
    public function getAdmin(){
        $data = request()->param();
        $token  = request()->header('token');
        $checkStatus = checkToken($token);
        $page = (int)$data['page'];
        $limit = (int)$data['limit'];
        unset($data['page']);
        unset($data['limit']);
        $field = 'admin_id,admin_roles,admin_head,admin_name,admin_status,admin_create_time,title,end_num,end_time,admin_remarks,enterprise_name';
        $my_data = Db::table('admin')
            ->alias('a')
            ->join('think_auth_group g','a.admin_roles=g.id')
            ->field($field)
            ->where('admin_id',$checkStatus['data']->uid)->find();
        switch ($my_data['admin_roles']){

            case 1:
                $admin_data = Db::table('admin')
                    ->alias('a')
                    ->join('think_auth_group g','a.admin_roles=g.id')
                    ->page($page,$limit)
                    ->where($data)
                    ->field($field)
                    ->select();
                $total = Db::table('admin')
                    ->where($data)
                    ->count();
                break;
            case 2:

                $admin_data = Db::table('admin')
                    ->alias('a')
                    ->join('think_auth_group g','a.admin_roles=g.id')
                    ->page($page,$limit)
                    ->where($data)
                    ->where('admin_pid',$checkStatus['data']->uid)
                    ->field($field)
                    ->select()->toArray();
                $total = Db::table('admin')
                    ->alias('a')
                    ->join('think_auth_group g','a.admin_roles=g.id')
                    ->where($data)
                    ->where('admin_pid',$checkStatus['data']->uid)
                    ->count();
                array_unshift($admin_data,$my_data);
                $total = $total+1;
                break;
            case 3:
                $admin_data = Db::table('admin')
                    ->alias('a')
                    ->join('think_auth_group g','a.admin_roles=g.id')
                    ->page($page,$limit)
                    ->where($data)
                    ->where('admin_id',$checkStatus['data']->uid)
                    ->field($field)
                    ->select();
                $total = Db::table('admin')
                    ->alias('a')
                    ->join('think_auth_group g','a.admin_roles=g.id')
                    ->where('admin_id',$checkStatus['data']->uid)
                    ->where($data)
                    ->count();

        }
        return json(['status'=>200,'msg'=>'ok','data'=>$admin_data,'total'=>$total]);
    }
    public function createAdmin(){
        $data = request()->param();
        $token  = request()->header('token');
        $checkToken = checkToken($token);
        $validate = new AdminValidate2();
        //设置admin_pid
        //取出admin_roles,如果admin_roles为 1 则设置 0，2设置为 当前自己的admin_id ,3禁止
        $admin_data = Db::table('admin')->where('admin_id',$checkToken['data']->uid)->find();
        $yanzheng = 'none';
        switch ($admin_data['admin_roles']){
            //超级用户
            case 1:
                $data['admin_pid'] = $admin_data['admin_id'];
                $yanzheng = 'super';
                $msg = $validate->check($data);
                break;
            case 2://业务员
                $data['admin_pid'] = $admin_data['admin_id'];
                //业务员账户添加时，没有rules，自动设置添加成普通用户
                if(!isset($data['admin_roles'])){
                    $data['admin_roles'] = 3;
                }
                $msg = $validate->check($data);
                $yanzheng = 'salesman';
                break;
            default:
                return json(['status'=>500,'msg'=>'普通用户禁止添加']);
                break;
        }
        if($msg === true){
            unset($data['admin_password2']);
            $admin_name =  Db::table("admin")->where("admin_name",$data['admin_name'])->find();
            if(!empty($admin_name)){
                return json(['status'=>500,'msg'=>'用户已存在！']);
            }
            //头像变量没有设置 和 头像为空
            if(!isset($data['admin_head'])||empty($data['admin_head'])){
                //默认头像
                $data['admin_head'] = 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png';
            }
            $set_password = set_password($data['admin_name'],$data['admin_password']);
            $new =   array_merge($data,$set_password);
//            var_dump($new);
            $res = Db::table('admin')->insert($new);
            if($res){
                return json(['status'=>200,'msg'=>'新增成功']);
            }else{
                return json(['status'=>500,'msg'=>'新增失败']);
            }
        }else{
            return json(['status'=>500,'msg'=>$validate->getError()]);
        }
    }
//    public function cs(){
//        $a = Db::table('admin')->where('admin_id',1)->withoutField('end_num')->update(['admin_name'=>'望东科技111']);
//        dump($a);
//    }
    public function updateAdmin(){
        $data = request()->param();
        $token = request()->header('token');
        $checkToken = checkToken($token);
        $AdminValidate3 = new AdminValidate3();
        unset($data['title']);
        $admin_id = $checkToken['data']->uid;
        $my_admin = Db::table('admin')->where('admin_id',$admin_id)->find();
       if($my_admin['admin_roles']==3){
           $check = $AdminValidate3->scene('update_admin_roles3')->check($data);
           if(!$check){return json(['status'=>500,'msg'=> $AdminValidate3->getError()]);}
            //普通用户不能让他修改end_time,end_num,admin_pid,admin_roles的字段,!!!!防止刷接口
           unset($data['admin_name'],$data['end_time'],$data['end_num'],$data['admin_pid'],$data['admin_roles'],$data['admin_password2']);
           if (isset($data['admin_password'])){$data['admin_password'] = password_hash($data['admin_password'],PASSWORD_DEFAULT);}
           $update = Db::table('admin')->where('admin_id',$admin_id)
               ->update($data);
       }else{
           $check = $AdminValidate3->check($data);
           if(!$check){return json(['status'=>500,'msg'=> $AdminValidate3->getError()]);}
           if (isset($data['admin_password'])){$data['admin_password'] = password_hash($data['admin_password'],PASSWORD_DEFAULT);}
           if(isset($data['admin_password2'])){ unset($data['admin_password2']);}
           if($my_admin['admin_roles'] == 2){unset($data['admin_roles']);}
           $update = Db::table('admin')->where('admin_id',$data['admin_id'])->update($data);
       }
        if($update){
            return json(['status'=>200,'msg'=>"修改成功"]);
        }else{
            return json(['status'=>500,'msg'=>"修改失败"]);
        }
    }
    public function delAdmin(){
        $data = request()->param();
        $token = request()->header('token');
        $checkToken = checkToken($token);
        $admin_id = $checkToken['data']->uid;
        $my_admin = Db::table('admin')->where('admin_id',$admin_id)->find();
        if($my_admin['admin_roles']==3){
            return json(['status'=>500,'msg'=>'普通用户禁止删除用户']);
        }else if($my_admin['admin_roles']==2){
            //登录用户为业务员，则不能删除管理员
            $del_admin = Db::table('admin')->where('admin_id',$data['admin_id'])->find();
            if($del_admin['admin_roles']<=2){
                return json(['status'=>500,'msg'=>'您没有足够权限删除管理员，只可删除普通用户']);
            }
        }
        $admin_head_url = Db::table('admin')->where('admin_id',$data['admin_id'])->value('admin_head');
        $url_arr = parse_url($admin_head_url);
        $head_url = $url_arr['host'];
        // 启动事务
        Db::startTrans();
        try {
            Db::table('forms')->where('admin_id',$data['admin_id'])->delete();
            Db::table('admin')->where('admin_id',$data['admin_id'])->delete();
            Db::table('messages')->where('admin_id',$data['admin_id'])->delete();
            $del_data= cutOutUrl($admin_head_url);
            //判断这个头像的url是否是当前域名的url
            if($_SERVER['HTTP_HOST']==$head_url){
                unlink($del_data['del_url']);
            }
            // 提交事务
            Db::commit();
            return json(['status'=>200,'msg'=>"删除成功"]);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['status'=>500,'msg'=>"删除失败"]);
        }
    }
    public function updateAdminStatus(){
        $data = request()->param();
        $token = request()->header('token');
        $checkToken = checkToken($token);
        $admin_id = $checkToken['data']->uid;
        $my_admin = Db::table('admin')->where('admin_id',$admin_id)->find();
        if($my_admin['admin_roles']==3){
            return json(['status'=>500,'msg'=>'普通用户禁止操作']);
        }else if($my_admin['admin_roles']==2){
            //登录用户为业务员，则不能删除管理员
            $del_admin = Db::table('admin')->where('admin_id',$data['admin_id'])->find();
            if($my_admin['admin_roles']<=2){
                return json(['status'=>500,'msg'=>'您没有足够权限操作管理员，只可操作普通用户']);
            }
        }
        switch ($data['admin_status']){
            case 0: $admin_status = 1;$msg='禁用';break;
            case 1: $admin_status = 0;$msg='启用';break;
        }
        $status = Db::table('admin')->where('admin_id',$data['admin_id'])->update(['admin_status'=>$admin_status]);
        if($status){
            return json(['status'=>200,'msg'=>$msg."成功"]);
        }else{
            return json(['status'=>500,'msg'=>$msg."失败"]);
        }

    }
    //取出角色
    public function getAuthGroup(){
        $data = Db::table('think_auth_group')->select();
        return json(['status'=>200,'data'=>$data]);
    }
    
}
